package org.example.exampreparationtreasure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.exampreparationtreasure.service.QuestionSelectorService;
import org.example.exampreparationtreasure.mapper.IncorrectQuestionRecordMapper;
import org.example.exampreparationtreasure.mapper.QuestionMapper;
import org.example.exampreparationtreasure.model.entity.ExamPaperConfig;
import org.example.exampreparationtreasure.model.entity.IncorrectQuestionRecord;
import org.example.exampreparationtreasure.model.entity.Question;
import org.example.exampreparationtreasure.model.entity.PracticeMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 专项训练题目选择器
 * 针对用户错题和薄弱知识点进行专项训练
 */
@Service
public class SpecializedQuestionSelectorServiceImpl implements QuestionSelectorService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private IncorrectQuestionRecordMapper incorrectQuestionRecordMapper;

    @Override
    public List<Question> selectQuestions(ExamPaperConfig config, Long userId) {
        List<Question> selectedQuestions = new ArrayList<>();
        Long categoryId = config.getCategoryId();

        // 1. 优先选择用户在指定科目的错题
        List<Long> incorrectQuestionIds = getIncorrectQuestionIds(userId, categoryId);
        if (!incorrectQuestionIds.isEmpty()) {
            List<Question> incorrectQuestions = questionMapper.selectBatchIds(incorrectQuestionIds);
            Collections.shuffle(incorrectQuestions);

            int incorrectCount = Math.min(
                    (int) (config.getQuestionCount() * 0.7),
                    incorrectQuestions.size()
            );
            selectedQuestions.addAll(incorrectQuestions.subList(0, incorrectCount));
        }

        // 2. 补充同科目的题目
        int remainingCount = config.getQuestionCount() - selectedQuestions.size();
        if (remainingCount > 0) {
            selectedQuestions.addAll(getAdditionalQuestions(
                    categoryId,
                    config.getInitialDifficulty(),
                    remainingCount,
                    selectedQuestions
            ));
        }

        return selectedQuestions;
    }





    private List<Long> getIncorrectQuestionIds(Long userId, Long categoryId) {
        QueryWrapper<IncorrectQuestionRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        // 如果指定了科目，需要关联查询题目表
        if (categoryId != null) {
            queryWrapper.inSql("question_id",
                    "SELECT question_id FROM questions WHERE category_id = " + categoryId);
        }

        queryWrapper.orderByDesc("mistake_count");

        List<IncorrectQuestionRecord> records = incorrectQuestionRecordMapper.selectList(queryWrapper);
        return records.stream()
                .map(IncorrectQuestionRecord::getQuestionId)
                .collect(Collectors.toList());
    }

    private List<Question> getAdditionalQuestions(Long categoryId, Integer initialDifficulty,
                                                  int count, List<Question> excludeQuestions) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();

        // 按科目筛选
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }

        // 按难度筛选
        queryWrapper.eq("difficulty", getDifficultyLevel(initialDifficulty));

        // 排除已选择的题目
        if (!excludeQuestions.isEmpty()) {
            List<Long> excludeIds = excludeQuestions.stream()
                    .map(Question::getQuestionId)
                    .collect(Collectors.toList());
            queryWrapper.notIn("question_id", excludeIds);
        }

        List<Question> allQuestions = questionMapper.selectList(queryWrapper);

        if (allQuestions.size() <= count) {
            return allQuestions;
        }

        Collections.shuffle(allQuestions);
        return allQuestions.subList(0, count);
    }


    private String getDifficultyLevel(Integer initialDifficulty) {
        switch (initialDifficulty) {
            case 1: return "易";
            case 2: return "中";
            case 3: return "难";
            default: return "易";
        }

    }
}